package com.wennn.top.generator.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.util.Properties;

@Slf4j
public class PropUtils {

    private static String SUFFIX_YAML_NAME = "yaml";
    private static String SUFFIX_PROP_NAME = "propterties";

    public static Properties getEnvYaml(String fileName){
        Resource resource = new ClassPathResource(fileName+"."+SUFFIX_YAML_NAME);
        Properties properties = null;
        try {
            YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
            yamlFactory.setResources(resource);
            properties = yamlFactory.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return properties;
    }

    public static Properties getEnvProp(String fileName){
        Resource resource = new ClassPathResource(fileName+"."+SUFFIX_PROP_NAME);
        Properties properties = null;
        try {
            PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
            propertiesFactoryBean.setLocation(resource);
            properties = propertiesFactoryBean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return properties;
    }

    public static Object getEnvValue(Object key){
        Properties properties = getEnvProp("application");
        if(null == properties){
            properties = getEnvYaml("application");
        }
        return null != properties?properties.get(key):null;
    }
}
